<?php
namespace catchAdmin\storehouse\model;

use catchAdmin\basics\model\Provider;
use catchAdmin\stock\model\Stock;
use catchAdmin\storehouse\model\search\ProjectSearch;
use catcher\base\CatchModel;
use catcher\CatchAuth;
use think\facade\Db;

class Project extends CatchModel
{

    use ProjectSearch;
    
    protected $name = 'db_project';
    protected $field = [
            'id', //
			'pid', // 父ID
			'project_id', // 项目编号
			'project_name', // 项目名称或委托人名称
			'describe', // 项目描述
			'tenant_id', // 商户id
            'creator_id', // 创建者ID
			'created_at', // 创建时间
			'updated_at', // 更新时间
			'deleted_at', // 删除状态，0未删除 >0 已删除
            'employees'
    ];
    /**
     * 用户列表
     *
     * @time 2019年12月08日
     * @return array|\think\Paginator
     *@throws \think\db\exception\DbException
     */
    public function getList($tenant_id=0)
    {
        $where = [];
        $where[] = ['pid','=',0];
        if($tenant_id){
            $where[] = ['tenant_id','=',$tenant_id];
        }
        return $this
            ->catchSearch()
            ->field('id,pid,project_id,project_name,tenant_id')
            ->where($where)
            ->order($this->aliasField('id'), 'desc')
            ->select()
            ->each(function (&$item){
                $item['children'] = $this
                    ->field('id,pid,project_id,project_name,tenant_id')
                    ->where([['tenant_id','=',$item['tenant_id']],['pid','=',$item['id']]])
                    ->select()
                    ->toArray();
            });
    }

    /**
     *  无分页列表
     *
     * @time 2019年12月08日
     * @return array|\think\Paginator
     *@throws \think\db\exception\DbException
     */
    public function getAttrList($tenant_id=0,$id=0,$position=0,$type=0)
    {
        $user = (new CatchAuth())->user();
        $user_id = $user->id;
        $where = [];
//        $where[] = ['pid','=',0];
        if($tenant_id){
            $where[] = ['tenant_id','=',$tenant_id];

            if($type==3){//员工账号，拿到所有项目
                $self_project = (new Project)
                    ->field('pid,project_id')
                    ->where([
                    ['pid','>',0],
                    ['tenant_id','=',$tenant_id],
                    ['employees','find in set', $user_id],
                ])->select()->toArray();

                $p_ids = array_column($self_project,'pid');
                $c_ids = array_column($self_project,'project_id');

                $where[] =  ['id','in',$p_ids];
            }else{
                $where[] = ['pid','=',0];
            }
        }
        $data = $this
            ->catchSearch()
            ->field('id,pid,project_id as value,project_name as label,tenant_id,describe,employees')
            ->where($where)
            ->order($this->aliasField('id'), 'asc')
            ->select();
        foreach($data as $k=>&$v){
            $map = [];
            if($tenant_id){
                $map[] = ['tenant_id','=',$tenant_id];
                if($type == 3){
                    $map[] = ['project_id','in',$c_ids];
                }
            }

            $map[] = ['pid','=',$v['id']];
            $ids = explode(',',$v['employees']);
            $data[$k]['staff']=Db::table('users')->where([['id','in',$ids]])->column('username');
            $data[$k]['staff']=implode(' / ',$data[$k]['staff']);
            $data[$k]['children'] = $this
                ->field('id,pid,project_id as value,project_name as label,tenant_id,describe,employees')
                ->where($map)
                ->select();
            if($data[$k]['children'] && count($data[$k]['children'])){
                foreach($data[$k]['children'] as $c=>$s){
                    $ids = explode(',',$s['employees']);
                    $data[$k]['children'][$c]['staff']=Db::table('users')->where([['id','in',$ids]])->column('username');
                    $data[$k]['children'][$c]['staff']=implode(' / ',$data[$k]['children'][$c]['staff']);
                }
            }
            //计算方
            $v['settlement'] = (new Provider)->where('id',$v['provider_id'])->value('settlement');
        }
        return  $data;
//        return $this
//            ->catchSearch()
//            ->field('id,pid,project_id as value,project_name as label,tenant_id,describe,employees')
//            ->where($where)
//            ->order($this->aliasField('id'), 'asc')
//            ->select()
//            ->each(function (&$item){
//                $item['children'] = $this
//                    ->field('id,pid,project_id as value,project_name as label,tenant_id,describe,employees')
//                    ->where([['tenant_id','=',$item['tenant_id']],['pid','=',$item['id']],['employees','like',"%$id%"]])
//                    ->select()
//                    ->toArray();
//            });
    }

     /**
	 * 父类ID查找子分类
	**/
	public function get_all_child_cate($catid,$str = ''){
    	$child = $this->where('pid',$catid)->column('id');
    	if($child){
	        $str .= ",".implode(',',$child);
	        foreach($child as $key => $val){
	            $str = $this->get_all_child_cate($val,$str);
	        }
	    }
	    return trim($str,',');
	}

    public function getTotalProjectNumber(){
        $user = (new CatchAuth)->user();

        $where = [
            ['deleted_at','=',0],
            ['pid','<>',0],
        ];

        if($user['type'] !== 1) {//普通商户
            $where[] = ['tenant_id','=',$user['tenant_id']];
        }

        $count = $this->where($where)->count();
        return $count;
    }
}
